﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain.Repositories;
using Domain.Entities;
using Database.NHibernateInterface;
using NHibernate.Criterion;

namespace Database.Repositories
{
   public class QuizRepository:BaseRepository<Quiz>, IQuizRepository
    {
       public QuizRepository(ISessionProvider sessionProvider):base(sessionProvider)
       { }

       public Quiz GetChapterResults(Chapter chapter, User user)
       {
           return Session.CreateCriteria<Quiz>().Add(Restrictions.Like("Chapter", chapter)).Add(Restrictions.Like("User", user)).List<Quiz>().LastOrDefault();
       }
       public IEnumerable<Quiz> GetTopicResults(Topic topic, User user)
       {
           if (topic != null)
           {
               var result = Session.CreateCriteria<Quiz>();
               ICriterion criteria = CreateTopicCriteria(topic);
               return result.Add(criteria).List<Quiz>();
           }
           else return null;
       }
       public IEnumerable<Quiz> GetCourseResults(Course course, User user)
       {
           if (course != null)
           {
               var result = Session.CreateCriteria<Quiz>();
               ICriterion criteria = null;
               foreach (var topic in course.Topics)
               {
                   if (criteria != null)
                   {
                       criteria = Restrictions.Or(criteria, CreateTopicCriteria(topic));
                   }
                   else
                   {
                       criteria = CreateTopicCriteria(topic);
                   }
               }
               criteria = Restrictions.And(criteria, Restrictions.Like("User", user));
               return result.Add(criteria).List<Quiz>();
           }
           else return null;
       }

       public IEnumerable<Quiz> GetSubjectedQuizes(User user)
       {
           if (user != null)
           {
               var result = Session.CreateCriteria<Quiz>().Add(
                   Restrictions.Like("User", user)).List<Quiz>();
               return result;
           }
           return null;

       }

       private ICriterion CreateTopicCriteria(Topic  topic)
       {
           ICriterion criteria = null;
           foreach (var chapter in topic.Chapters)
           {
               if (criteria != null)
               {
                   criteria = Restrictions.Or(Restrictions.Like("Chapter", chapter), criteria);
               }
               else
               {
                   criteria = Restrictions.Like("Chapter", chapter);
               }
           }
           return criteria;
       }
    }
}
